import { MessageTypeEnum } from '@/enums';
import * as signalR from '@microsoft/signalr';
import useStore from '@/store';
import { ElNotification } from 'element-plus';

export default class SignalR {
  url: string;
  signalr: signalR.HubConnection | null;
  connectionId: string;
  constructor(url?: string) {
    this.url = url ?? 'https://localhost:9000/admin/InformHub'; // 坑点1
    this.connectionId = '';
    this.signalr = null;
  }
  doOpen() {
    const signalr = new signalR.HubConnectionBuilder()
      .withUrl(this.url, {
        //headers: { authorization: 'Bearer ' + useStore.setting.getToken },
        //skipNegotiation: true,
        transport: signalR.HttpTransportType.LongPolling,
        accessTokenFactory: () => useStore.setting.token,
      })
      .withAutomaticReconnect() // 自动断开重连
      .build();
    //signalr.start();
    return new Promise((resolve, reject) => {
      signalr
        .start() // 启动连接
        .then(() => {
          this.connectionId = signalr.connectionId ?? '';
          this.signalr = signalr;
          resolve(signalr);
        })
        .catch(e => {
          reject(e);
        });
    });
  }

  async sendMessage(messageType: MessageTypeEnum, params: any) {
    // 发送请求
    try {
      await this.signalr.invoke(messageType.toString(), params); // 坑点二
    } catch (error) {
      console.error(error, messageType.toString());
    }
  }
  ReceiveMessage() {
    this.signalr.on(MessageTypeEnum[MessageTypeEnum.NewMessage], user => {
      ElNotification.success({
        title: '您有一条新消息通知',
        message: '来自用户' + user.Name,
      });
    });
  }
}
